//登录与注册模块
import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from '@/api'
import { setToken, getToken, removeToken } from '@/utils/token';
const state = {
    code: '',
    token: getToken(),
    userInfo: {}
};
const mutations = {
    GETCOOE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo ||{}
    },
    CLEAR(state) {
        state.token = ''
        state.userInfo = {};
        removeToken()
    }
};
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone)
        console.log(result);
        if (result.code == 200) {
            commit('GETCOOE', result.data);
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户注册
    async UserRegister({ commit }, user) {
        //全部表单验证成功，在向服务器发请求，进行祖册
        // let success = await this.$validator.validateAll();
        // console.log(success,'111');
        let result = await reqUserRegister(user)
        console.log(result,'222');
        if (result.code == 200) {
            commit('GETCOOE', result.data);
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户登录
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        console.log(result);
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
            setToken(result.data.token);
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //获取用户信息
    async getUserInfo({ commit }) {
        let result = await reqUserInfo()
        console.log(result,'111');
        if (result.code == 200) {
            commit('GETUSERINFO', result.data)
            return 'ok'
        } else {
            return '用户未登录'
        }
    },
    //退出登录
    async userLogout({ commit }) {
        let result = await reqLogout()
        console.log(result);
        if (result.code == 200) {
            commit('CLEAR')
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
};
const getters = {};
export default {
    state,
    mutations,
    actions,
    getters,
};
